import { useEffect } from "react";
import {
  Button,
  Table,
  TableProps,
  Modal,
  Input,
  message,
  Flex,
  Dropdown,
  Form,
  Space,
  Tooltip,
} from "antd";
import { POST_MSG_TYPE } from "@/utils/enums";
import { BVID_CONCLUSION_KEY, getBvidSubtitle } from "@/utils/bilibili";
import { stringToPDFDownload } from "@/utils/pdf.ts";
import _ from "lodash";
import { useOperation } from "./hooks";
import { SettingOutlined, SnippetsOutlined } from "@ant-design/icons";
const { success } = Modal;
function Bilibili() {
  const [form] = Form.useForm();
  const {
    handleDownloadComments,
    addByBvid,
    bvidList,
    refreshBvidList,
    sendTongyiSummary,
    sendDoubaoSummary,
    onOpenConfigModal,
  } = useOperation();

  const handleDelete = async (bvid: string) => {
    const result = await chrome.storage.local.get([BVID_CONCLUSION_KEY]);
    const _bvidList = result[BVID_CONCLUSION_KEY];
    const bvidList: any[] = _.filter(
      _bvidList,
      (data: any) => data.bvid !== bvid
    );
    chrome.storage.local.set({ [BVID_CONCLUSION_KEY]: bvidList });
    refreshBvidList();
  };

  const handleDownLoad = async (bvid: string, title: string) => {
    const c = await getBvidSubtitle(bvid);
    stringToPDFDownload(c, title);
  };

  const showConfirm = async (bvid: string, title: string, cid?: string) => {
    const hide = message.loading("正在获取字幕详情", 0);
    const text = await getBvidSubtitle(bvid, cid);
    hide();
    success({
      title,
      maskClosable: true,
      content: (
        <Input.TextArea
          defaultValue={text}
          autoSize={{ maxRows: 20, minRows: 10 }}
        />
      ),
    });
  };

  useEffect(() => {
    refreshBvidList();
    chrome.runtime.onMessage.addListener(function (e, sender, sendResponse) {
      if (e.type === POST_MSG_TYPE.conclusion) {
        refreshBvidList();
      }
    });
  }, []);

  const columns: TableProps["columns"] = [
    {
      title: "标题",
      dataIndex: "title",
      ellipsis: true,
      width: 150,
      render: (value, record) => {
        const { bvid, isLeaf, page } = record;
        return (
          <a
            href={`https://www.bilibili.com/video/${bvid}${
              isLeaf ? `?p=${page}` : ""
            }`}
            target="_blank"
          >
            {value}
          </a>
        );
      },
    },
    {
      title: "UP主",
      dataIndex: "owner",
      ellipsis: true,
      width: 100,
      render: (value, record) => {
        if (_.isNil(value)) return "-";
        const { mid, name } = value;
        return (
          <a href={`https://space.bilibili.com/${mid}`} target="_blank">
            {name}
          </a>
        );
      },
    },
    {
      title: "操作",
      dataIndex: "view",
      width: 100,
      fixed: "right",
      render: (value, record) => {
        const { title, bvid, pages, cid, isLeaf } = record;
        return (
          <Flex justify="flex-end" align="center" style={{ width: "100%" }}>
            {(pages?.length || 0) <= 1 && (
              <Button type="link" onClick={() => showConfirm(bvid, title, cid)}>
                字幕
              </Button>
            )}
            <Dropdown
              menu={{
                items: _.compact([
                  {
                    label: (
                      <a
                        type="link"
                        onClick={() => handleDownLoad(bvid, title)}
                      >
                        下载字幕
                      </a>
                    ),
                    key: "0",
                  },
                  {
                    label: (
                      <a
                        type="link"
                        onClick={() =>
                          handleDownloadComments(bvid, `${title}评论区数据`)
                        }
                      >
                        下载评论
                      </a>
                    ),
                    key: "2",
                  },
                  {
                    label: (
                      <a
                        type="link"
                        onClick={() => sendTongyiSummary(bvid, cid)}
                      >
                        通义总结
                      </a>
                    ),
                    key: "qianwen",
                  },
                  {
                    label: (
                      <a
                        type="link"
                        onClick={() => sendDoubaoSummary(bvid, cid)}
                      >
                        豆包总结
                      </a>
                    ),
                    key: "doubao",
                  },
                  !isLeaf && {
                    label: (
                      <a type="link" onClick={() => handleDelete(bvid)}>
                        删除
                      </a>
                    ),
                    key: "delete",
                  },
                ]),
              }}
            >
              <a onClick={(e) => e.preventDefault()}>更多</a>
            </Dropdown>
          </Flex>
        );
      },
    },
  ];

  return (
    <>
      <Flex justify="space-between" vertical>
        <Form
          form={form}
          layout="inline"
          onFinish={async (values) => {
            await addByBvid(values.bvid);
            form.resetFields();
          }}
        >
          <Form.Item
            label="BV号"
            name="bvid"
            rules={[
              {
                required: true,
                message: "请输入B站视频链接或者BV号",
              },
            ]}
          >
            <Input placeholder="BV号" />
          </Form.Item>
          <Form.Item>
            <Button size="small" type="primary" htmlType="submit">
              添加
            </Button>
          </Form.Item>
        </Form>
        <Space>
          <Button
            size="small"
            icon={<SettingOutlined />}
            onClick={onOpenConfigModal}
          />
          <Tooltip title="从剪贴板粘贴BV号">
            <Button
              size="small"
              icon={<SnippetsOutlined />}
              onClick={() => {
                navigator.clipboard.readText().then((text) => {
                  addByBvid(text);
                });
              }}
            />
          </Tooltip>
        </Space>
      </Flex>

      <Table
        rowKey="cid"
        columns={columns}
        dataSource={bvidList}
        childrenColumnName="pages"
        size="small"
      />
    </>
  );
}

export default Bilibili;
